// 学生管理
const {student,audit,userInfo,schoolInfo,studentManifestation,studentScores,roleSys,rank_sys, sequelize} = require('../dbConfig/index.js')

const { Op } = require('sequelize');
// 
const addStudent = async (ctx,next) => {
	const {student_name,student_sex,student_age,student_address,student_phone,student_school,student_grade,student_class,specialty_id,student_pic_head,student_pic_idcard,guardian_phone,guardian_name } = ctx.request.body
	if( !(student_name && student_phone && student_school && student_grade && student_class && specialty_id && student_pic_idcard && guardian_phone && guardian_name)){
		ctx.body = {
			code:1,
			msg:'参数不全'
		}
	}else{
		const transaction = await sequelize.transaction()
		await student.create({
			student_name,
			student_sex,
			student_age,
			student_address,
			student_phone,
			student_school,
			student_grade,
			student_class,
			specialty_id,
			student_pic_head,
			student_pic_idcard,
			guardian_phone,
			guardian_name
		},{ transaction })
		// 将该院校的学生人数加1
		await schoolInfo.update({
			school_student_num:sequelize.literal('school_student_num+1')
		},{
			where:{
				school_id:student_school
			},
			transaction
		})
		transaction.commit()
		ctx.body = {
			code:0,
			msg:'添加成功'
		}	
	}
}
// 获取学生列表 入参 所属院校(必须) 学生姓名(非必须) 年级(非必须) 班级(非必须) 页码 条数 
const getStudentList = async (ctx,next) => {
	const { student_name,student_grade,student_class,page,limit,student_school } = ctx.request.body
	if( !(page && limit&&student_school)){
		ctx.body = {
			code:1,
			msg:'参数不全'
		}
	}else{
		const where = {}
		if(student_name) where.student_name = student_name
		if(student_grade) where.student_grade = student_grade
		if(student_class) where.student_class = student_class
		if(student_school) where.student_school = student_school
		
		const result = await student.findAndCountAll({
			where,
			offset: (page - 1) * limit,
			limit
		})
		ctx.body = {
			code:0,
			msg:'查询成功',
			data:result.rows,
			total:result.count
		}
	}
}
		
// 申请修改学生信息 需先查询有无审核记录 如果没有 则查询权限具有该院校学生年级或班级具有审核权限的用户 并写入记录 入参 学生id(必须) 申请人id(必须) 申请备注(必须) school_id(必须) 
const studentAuditSubmit = async (ctx, next) => {
    try {
        const { student_id, proposer_id, audit_remark, school_id } = ctx.request.body;
        if (!student_id || !proposer_id || !audit_remark || !school_id) {
            ctx.status = 400;
            ctx.body = { code: 1, msg: '参数不全: student_id, proposer_id, audit_remark 或 school_id' };
            return;
        }

        // 检查是否有未完成的审核记录
        const existingAudit = await audit.findOne({
            where: {
                student_id,
                proposer_state: { [Op.or]: ['1', '4'] } // 待审核或已修改
            }
        });

        if (existingAudit) {
            ctx.body = { code: 1, msg: '该学生已有未完成的审核记录' };
            return;
        }

        // 查询审核人（院校负责人或教职工，且具有页面ID=6和功能权限65）
        const user = await userInfo.findOne({
            where: {
                belong_to_school: school_id,
                identity: { [Op.or]: ['1', '2'] } // 1-院校负责人 2-教职工
            },
            logging: console.log // 打印SQL日志
        });

        if (!user) {
            ctx.status = 400;
            ctx.body = { code: 1, msg: '未找到符合条件的用户' };
            return;
        }

        // 查询 role_sys 和 rank_sys
        const role = await roleSys.findOne({
            where: { role_id: user.user_id },
            include: [{
                model: rank_sys,
                as: 'rank_sys',
                where: {
                    page_id: 6,
                    page_function_ids: { [Op.like]: '%65%' }
                }
            }]
        });

        if (!role || !role.rank_sys) {
            ctx.status = 400;
            ctx.body = { code: 1, msg: '未找到符合条件的审核人' };
            return;
        }

        const auditor = user;

        if (!auditor) {
            ctx.status = 400;
            ctx.body = { code: 1, msg: '未找到符合条件的审核人' };
            return;
        }

        // 创建审核记录
        await audit.create({
            student_id,
            proposer_id,
            audit_remark,
            school_id,
            audit_person_id: auditor.user_id, // 设置审核人
            proposer_state: '1', // 待审核
            proposer_timer: new Date()
        });

        ctx.body = { code: 0, msg: '申请提交成功' };
    } catch (error) {
		console.log(error,'申请修改错误')
        ctx.status = 500;
        ctx.body = { code: 1, msg: '服务器错误', error: error.message };
    }
}
// 审核 入参 审核人id(必须) 审核记录id(必须)
const auditStu = async (ctx,next)=>{
	const { id } = ctx.request.body
	const user_id = ctx.status.user_id
	if(!id){
		ctx.body = {
			code:1,
			msg:'参数不全'
		}
	}else{
		const result = await audit.findOne({
			where:{
				id
			}
		})
		if(result){
			if(result.audit_person_id == user_id){
				await audit.update({
					proposer_state:'2'
				},{
					where:{
						id
					}
				})
				ctx.body = {
					code:0,
					msg:'审核成功'
				}
			}
		}else{
			ctx.body = {
				code:1,
				msg:'审核记录不存在'
			}
		}
	}	
}
// 修改学生信息
const editStudent = async (ctx,next)=>{
	const { id,student_name,student_sex,student_age,student_address,student_phone,student_grade,student_class,specialty_id,student_pic_head,student_pic_idcard,guardian_phone,guardian_name } = ctx.request.body
	if( !(id && student_name && student_phone && specialty_id && student_pic_idcard && guardian_phone && guardian_name)){
		ctx.body = {
			code:1,
			msg:'参数不全'
		}
	}else{
		const transaction = await sequelize.transaction()
		await student.update({
			student_name,
			student_sex,
			student_age,
			student_address,
			student_phone,
			student_grade,
			student_class,
			specialty_id,
			student_pic_head,
			student_pic_idcard,
			guardian_phone,
			guardian_name
		},{
			where:{
				id
			},
			transaction
		})
		// 删除 关于该学生的审核记录
		await audit.destroy({
			where:{
				student_id:id
			},
			transaction
		})
		await transaction.commit()
		ctx.body = {
			code:0,
			msg:'修改成功'
		}	
	}
}
// 删除
const del = async (ctx,next)=>{
		const { id } = ctx.request.body
		if(!id){
			ctx.body = {
				code:1,
				msg:'参数不全'
			}
		}else{
			const transaction = await sequelize.transaction()
			await student.destroy({
				where:{
					id
				}
			},{ transaction })
			// 学校学生人数减1
			await school.update({
				school_student_num:sequelize.literal('school_student_num-1')
			},{
				where:{
					school_id
				},
				transaction
			})	
			await transaction.commit()
			ctx.body = {
				code:0,
				msg:'删除成功'
			}
		}	
}
// 新增表现 入参 学生id(必须) 表现内容(必须)
const addStudentManifestation = async (ctx,next)=>{
	const { student_id, manifestation_content } = ctx.request.body
	if(!(student_id && manifestation_content)){
		ctx.body = {
			code:1,
			msg:'参数不全'
		}
	}else{
		await studentManifestation.create({
			student_id,
			manifestation_content
		})
		ctx.body = {
			code:0,
			msg:'新增成功'
		}
	}
}
// 新增学分 入参 学分 学生id
const addStudentCredit = async (ctx,next)=>{
	const { student_id, student_score } = ctx.request.body
	if(!(student_id && student_score)){
		ctx.body = {
			code:1,
			msg:'参数不全'
		}
	}else{
		await studentScores.create({
			student_id,
			student_score
		})
		ctx.body = {
			code:0,
			msg:'新增成功'
		}
	}	
}
// 查询当前学生的表现(studentManifestation) 和学分(studentScores)情况
const getStudentDetail = async (ctx,next)=>{
	const { id } = ctx.request.body
	if(!id){
		ctx.body = {
			code:1,
			msg:'参数不全'
		}
	}else{
		const result = await studentManifestation.findAll({
			where:{
				student_id:id
			}
		})
		const result2 = await studentScores.findAll({
			where:{
				student_id:id
			}
		})
		ctx.body = {
			code:0,
			msg:'查询成功',
			data:{
				studentManifestation:result,
				studentScores:result2
			}
		}
	}
}
// 查询当前用户是审核者还是提交审核者  是否有待审核或审核通过待修改的任务
const getStudentAudit = async (ctx,next)=>{
	const user_id = ctx.status.user_id
	const result = await audit.findAll({
		where:{
			audit_person_id:user_id,
			proposer_state:'1'
		}
	})
	const result2 = await audit.findAll({
		where:{
			proposer_id:user_id,
			proposer_state:'2'
		}
	})
	ctx.body = {
		code:0,
		msg:'查询成功',
		data:{
			audit:result,
			audit2:result2
		}
	}
}
module.exports = {
	getStudentList,
	addStudent,
	studentAuditSubmit,
	auditStu,
	editStudent,
	del,
	addStudentManifestation,
	addStudentCredit,
	getStudentDetail,
	getStudentAudit
}